package es.usc.citius.servando.calendula.util.alerts;

import org.joda.time.LocalDate;

import java.util.List;

import es.usc.citius.servando.calendula.CalendulaApp;
import es.usc.citius.servando.calendula.database.DB;
import es.usc.citius.servando.calendula.events.StockRunningOutEvent;
import es.usc.citius.servando.calendula.persistence.Medicine;
import es.usc.citius.servando.calendula.persistence.PatientAlert;
import es.usc.citius.servando.calendula.persistence.alerts.StockRunningOutAlert;
import es.usc.citius.servando.calendula.util.PreferenceKeys;
import es.usc.citius.servando.calendula.util.PreferenceUtils;
import es.usc.citius.servando.calendula.util.stock.MedicineScheduleStockProvider;
import es.usc.citius.servando.calendula.util.stock.StockCalculator;


public class StockAlertHandler {


    public static void checkStockAlerts(Medicine m) {
        if (m.stockManagementEnabled()) {

            StockCalculator.StockEnd stockEnd = StockCalculator.calculateStockEnd(
                    LocalDate.now(),
                    new MedicineScheduleStockProvider(m),
                    m.getStock()
            );

            int stockAlertPref = Integer.parseInt(
                    PreferenceUtils.getString(
                            PreferenceKeys.SETTINGS_STOCK_ALERT_DAYS,
                            "-1"
                    )
            );
            List<PatientAlert> alerts =
                    DB.alerts().findByMedicineAndType(m, StockRunningOutAlert.class.getCanonicalName());

            if (stockEnd instanceof StockCalculator.StockEnd.OnDate && ((StockCalculator.StockEnd.OnDate) stockEnd).getDays() < stockAlertPref && alerts.isEmpty()) {
                // if there are no alerts but the stock is under the preference, create them
                AlertManager.createAlert(new StockRunningOutAlert(m, LocalDate.now()));
                CalendulaApp.eventBus().post(new StockRunningOutEvent(m, ((StockCalculator.StockEnd.OnDate) stockEnd).getDays()));
            } else if (!alerts.isEmpty() && ((stockEnd instanceof StockCalculator.StockEnd.OnDate && ((StockCalculator.StockEnd.OnDate) stockEnd).getDays() >= stockAlertPref) || stockEnd instanceof StockCalculator.StockEnd.OverMax)) {
                // if there are alerts but the stock is over the pref (or over the max) remove them
                for (PatientAlert a : alerts) {
                    AlertManager.removeAlert(a);
                }
            }
        }

    }
}
